/*
求多项式的值
*/

#include<iostream>
using namespace std;

// 解法1
double solve1(double a[], int n, double x)	 
{
	double p=0.0, p1;
	for (int i=n; i>=0; i--)
	{
		p1 = 1.0;
		for (int j=1;j<=i;j++)
			p1 *= x;
		p += p1 * a[i];
	}
	return p;
}

// 求多项式值的递归算法
double Horner(double a[], int n, double x, int i)  
{
	if (i==0)
		return a[n];
	else
		return x*Horner(a,n,x,i-1)+a[n-i];
}

// 解法2
double solve2(double a[], int n, double x)
{
	return Horner(a,n,x,n); 
} 

int main()
{
	// 初始化数组
	double a[]={5, -2, 3};
	
	// 求数组长度
	int n = sizeof(a) / sizeof(a[0]) - 1;
	
	// 给x赋值
	double x = 0.5;
	
	// %g自动选择 小数或指数形式输出
	printf("x=%g的结果:\n", x);
	printf("  P=%g\n", solve1(a, n, x));
	printf("  P=%g\n", solve2(a, n, x));
	
	// 给x赋值
	x = -0.2;
	printf("x=%g的结果:\n",x);
	printf("  P=%g\n", solve1(a, n, x));
	printf("  P=%g\n", solve2(a, n, x));
	return 0;
}
